<template>
  <div class="overtime-calender-card cell" :class="[`calender-week-${date.getDay()}`, tagStatus && `lagal-type-${tagStatus.legalType}`]">
    <div class="day" @click="handleClickBtnOpenDialog()">
      <div class="div-1">
        {{ date.getDate() }}<span v-if="tagStatus" class="day-status">({{ tagStatus.legalTypeLabel }})</span>
      </div>
      <div class="div-300">
        <div v-if="clockinInfo && clockinInfo.mornin !== ''">早：{{ clockinInfo.mornin }}</div>
        <div v-else><el-tag type="danger">早卡未打</el-tag></div>
        <div v-if="clockinInfo && clockinInfo.evening !== ''">晚：{{ clockinInfo.evening }}</div>
        <div v-else><el-tag type="danger">晚卡未打</el-tag></div>
      </div>
      <el-popover placement="top" v-if="currentStatus.type !== ''" width="300">
        <template #reference>
          <div class="div-3">
            <div class="tag-cell">
              <el-card class="overtime-calendar-card" :class="currentStatus.type">
                <div class="overtime-calendar-card-body">
                  <el-text :type="currentStatus.type">开始时间：{{ itemData.startTime }}</el-text>
                  <br />
                  <el-text :type="currentStatus.type">结束时间：{{ itemData.endTime }}</el-text>
                </div>
              </el-card>
            </div>
          </div>
        </template>

        <el-descriptions class="margin-top" :column="1" border>
          <el-descriptions-item>
            <template #label>开始时间：</template>
            {{ itemData.startTime }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>结束时间：</template>
            {{ itemData.endTime }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>工作内容：</template>
            <div class="remark-content">
              {{ itemData.remark }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item v-if="itemData.overtimeStatus == 1">
            <template #label>当前审批人：</template>
            <div class="remark-content">{{ itemData.approvalUserNick }} - {{ itemData.approvalUserName }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </el-popover>
      <div v-if="btnShowFlag && currentStatus.type == ''" class="btn-container">
        <el-button type="primary" size="large">补加班</el-button>
      </div>
    </div>

    <OvertimeStatusTag v-if="currentStatus.type !== ''" class="tag" :status="itemData.overtimeStatus * 1" />
    <el-button class="btn-delete" type="danger" @click="handleClickBtnDelete()" :icon="Delete" text v-if="currentStatus.type !== ''" circle />
  </div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { Delete } from '@element-plus/icons-vue'
import { overtimeStatus } from '../../definitions/status'
import { ElMessage } from 'element-plus'
import { formatDate } from '../../utils'
import { useUsersStore } from '../../stores'
import OvertimeStatusTag from './OvertimeStatusTag.vue'

const emit = defineEmits(['click', 'delete'])

const props = defineProps({
  date: {
    required: true,
    type: Date || null,
    default: () => {},
  },
  itemData: {
    required: true,
    type: Object || null,
    default: () => {},
  },
  clockinInfo: {
    type: Object as any,
    default: () => ({
      mornin: '',
      evening: '',
    }),
  },
  legalList: {
    type: Array as any,
    default: () => [],
  },
})

// 当天是否为节假日
const currentStatus = computed(() => {
  // console.log(props.itemData)
  if (props.itemData && props.itemData.overtimeStatus !== undefined) {
    const [text, type] = overtimeStatus[props.itemData.overtimeStatus]
    return {
      text,
      type,
    }
  } else {
    return {
      text: '',
      type: '',
    }
  }
})

// 补卡按钮是否显示逻辑
const btnShowFlag = computed(() => {
  let flag = false
  // 判断是否是工作日
  // console.log('tagStatus.value', formatDate(props.date), tagStatus.value)

  if (tagStatus.value && tagStatus.value.legalType == 1) {
    // 周一至周五 调休 休息 / 法定休息
    // console.log('周一至周五 调休 休息 / 法定休息', formatDate(props.date), tagStatus.value)
    if (props.clockinInfo && props.clockinInfo.mornin && props.clockinInfo.evening) {
      flag = true
    } else {
      flag = false
    }
  } else if (tagStatus.value && tagStatus.value.legalType == 2) {
    // 周六或周日 调休 工作 / 法定工作
    // console.log('周六或周日 调休 工作 / 法定工作', formatDate(props.date), tagStatus.value)
    if (props.clockinInfo && props.clockinInfo.mornin && props.clockinInfo.evening) {
      flag = isOvertimeQualified()
    } else {
      flag = false
    }
  } else {
    // 周一至周五 || 周六或周日 调休 上班 / 法定上班
    // console.log('周一至周五 ', formatDate(props.date), tagStatus.value)
    if (props.clockinInfo && props.clockinInfo.mornin && props.clockinInfo.evening) {
      if (props.date.getDay() == 6 || props.date.getDay() == 0) {
        // 周六或周日
        flag = true
      } else {
        // 工作日
        flag = isOvertimeQualified()
      }
    } else {
      // 无早或晚打卡记录，则显示补卡按钮
      flag = false
    }
  }
  return flag
})

// 计算是否满足加班条件
const isOvertimeQualified = (): boolean => {
  const workingDay = new Date(props.date)
  const startOfDay = new Date(props.date)

  const [hour1, minute1] = props.clockinInfo.evening.split(':').map(Number)
  workingDay.setHours(hour1, minute1, 0, 0)

  const { startOvertimeTime, city } = useUsersStore().user as any
  if (startOvertimeTime) {
    // 设置加班开始时间
    const t = startOvertimeTime.split(':').map(Number)
    startOfDay.setHours(t[0], t[1], 0, 0)
  }
  let len = 0
  if (city == '北京') {
    // >= 60 分钟
    len = 3600000
  } else {
    // >= 30 分钟
    len = 1800000
  }
  // 工作时间 - 加班开始时间 > 城市最小加班时间
  return workingDay.getTime() - startOfDay.getTime() >= len
}

// 当天是否为节假日
const tagStatus = computed(() => {
  const legal = props.legalList.find((item: any) => item.legalDate == formatDate(props.date, 'yyyy-MM-dd'))
  let result: any = null

  if (legal) {
    result = {
      legalType: legal.legalType,
      legalTypeLabel: legal.legalTypeLabel,
    }
  }
  return result
})

const handleClickBtnOpenDialog = () => {
  const { mornin, evening } = props.clockinInfo
  if (mornin == '' || evening == '') {
    ElMessage.error(`请先完成 ${formatDate(props.date, 'yyyy-MM-dd')} 上班打卡！`)
  } else if (btnShowFlag.value && currentStatus.value.type == '') {
    emit('click', { date: props.date, isComp: btnShowFlag.value, clockinInfo: props.clockinInfo })
  } else {
    // ElMessage.warning('不需要')
  }
}
const handleClickBtnDelete = () => {
  emit('delete', props.itemData.id)
}
</script>
<style lang="scss" scoped>
.overtime-calender-card.cell {
  width: 100%;
  height: 100%;
  position: relative;
  .btn-container {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
  }
  .btn-delete {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 99;
  }
  .tag-cell {
    margin-bottom: 0px;
    .tag {
      width: 100%;
    }
  }
  .tag {
    position: absolute;
    top: 4px;
    right: 30px;
  }
  .overtime-calendar-card {
    margin-top: 20px;
    width: 100%;
    &.primary {
      background-color: rgb(235.9, 245.3, 255);
      border-color: rgb(121.3, 187.1, 255);
    }
    &.danger {
      background-color: rgb(254, 240.3, 240.3);
      border-color: rgb(248, 152.1, 152.1);
    }
    &.success {
      background-color: rgb(239.8, 248.9, 235.3);
      border-color: rgb(148.6, 212.3, 117.1);
    }

    .overtime-calendar-card-body {
      margin: -20px;
      text-align: center;
    }
  }
  .day {
    height: 100%;
    width: 100%;
    position: absolute !important;
  }
  .div-300 {
    display: flex;
    justify-self: center;
    div {
      flex: 1;
    }
  }
  .div-1 {
    font-size: 28px;
    position: relative !important;
    display: flex;
    align-items: center;
    .day-status {
      font-size: 16px;
      display: block;
      margin-left: 12px;
    }
  }
  .div-2 {
    position: absolute;
    top: 0;
    right: 0;
    opacity: 0;
    transition: all 0.3s ease;
  }
  .div-3 {
    pointer-events: initial !important;
    text-align: left;
    bottom: 0;
    flex: 1;
    width: 100%;

    div {
      & + div {
        margin-top: 0;
      }
    }
  }
  &:hover {
    .div-2 {
      opacity: 1;
    }
  }
}
</style>
